package com.databaseManager;

import com.vo.DispensingVo;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 同类型的数据DAOimpl
 */
public class DatabaseFunc2 extends DatabaseManager implements IdatabaseFunc2{

    /**
     * 处方药物简要信息
     */
    class medicineBriefMsg{
        String drugId;
        Integer drugQuan;
        public medicineBriefMsg(String drugId, Integer drugQuan) {
            this.drugId = drugId;
            this.drugQuan = drugQuan;
        }
    }

    /**
     * 通过诊断的id获取处方的信息，找出所有诊断id相同的并整合为一个Vo类
     * @param id 诊断id
     * @return 视图准JSON对象
     */
    @Override
    public DispensingVo getDispensingMsg(String id) {
        String selectIdSql="SELECT PrescribeId FROM table_prescription WHERE Pid=?";
        String sql="SELECT Process FROM table_prescription_medicine WHERE PrescribeId = ?;";
        Connection conn = null; // 得到数据库连接
        try {
            ResultSet prescribeRs = executeSQL(conn, selectIdSql, SqlOP.SELECT, new Object[]{id});
            int flag=0;
            while (prescribeRs.next()){
                flag=1;
                ResultSet resultSetId=executeSQL(conn,sql,SqlOP.SELECT,new Object[] {prescribeRs.getString("PrescribeId")} );
                if(Integer.valueOf(resultSetId.getString("Process"))>3){
                    String diagId=prescribeRs.getString("PrescribeId");
                    String[] diagID=new String[] {diagId};
                    String mySql = "SELECT MedId,Consum FROM TABLE_PRESCRIPTION_MEDICINE where diagId=?";
                    System.out.println(mySql);
                    ResultSet resultSet=null;
                    try {
                        resultSet=executeSQL(conn, mySql, SqlOP.INSERT, diagID);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                    try {
                        DatabaseManager.closeAll(conn, null, null);
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                    List<Object> drug=new ArrayList<>();
                    /**
                     * 循环诊断号，遇到符合条件的就操作，操作结束直接返回，不用break
                     */
                    while (true) {
                        try {
                            if (!resultSet.next()) break;

                            drug.add(new medicineBriefMsg(resultSet.getString("MedId"),resultSet.getInt("Consum")));
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                    DispensingVo dispensingMsg=new DispensingVo(getPidByDiagId(diagId),diagId,drug);
                    return dispensingMsg;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过病号的诊断号码获取身份证
     * @param diaId 诊断id
     * @return 身份证号码
     */
    @Override
    public String getPidByDiagId(String diaId) {
        //预处理sql
        String sql = "SELECT Pid FROM table_diagnosis WHERE DiagId = ?;";
        Connection conn = null; // 得到数据库连接
        /**
         * 病人身份证号
         */
        String p = null;
        try {
            conn = getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        ResultSet rs = null;
        try {
            rs = executeSQL(conn, sql, SqlOP.SELECT, new Object[] {diaId});

            while(rs.next())
            {
                p=rs.getString("Pid");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            DatabaseManager.closeAll(conn, null, null);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return p;
    }

    class prescribeIdMedMsg{
        String PrescribeId;
        String Process;
    }
    /**
     * 先查询出信息，再筛选出处方号
     * 获取处方状态，无信息为0，其余直接返回了数据库中的信息
     * @param id 身份证号
     * @return 处方状态
     */
    @Override
    public String getProgressState(String id){
        String selectIdSql="SELECT PrescribeId FROM table_prescription WHERE Pid=?";
        String o = null;
        String sql="SELECT Process FROM table_prescription_medicine WHERE PrescribeId = ?;";
        Connection connection;
        try {
            connection =getConnection();
            ResultSet prescribeRs = executeSQL(connection, selectIdSql, SqlOP.SELECT, new Object[]{id});
            int flag=0;
            while (prescribeRs.next()){
                flag=1;
                ResultSet resultSet=executeSQL(connection,sql,SqlOP.SELECT,new Object[] {prescribeRs.getString("PrescribeId")} );
                if(Integer.valueOf(resultSet.getString("Process"))>3){
                    o=resultSet.getString("Process");
                    break;
                }
            }
            if(flag==0) {
                o = "0";
            }
        }catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return o;
    }

    /**
     * 首先获取处方的内容，然后逐项进行数据库操作，
     * @param prescriptionNum
     */
    @Override
    public void dispensing(String prescriptionNum) {
        Connection conn = null; // 得到数据库连接
        try {
            conn = getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        String[] diagID=new String[] {prescriptionNum};
        String mySql = "SELECT MedId,Consum FROM TABLE_PRESCRIPTION_MEDICINE where diagId=?";
        System.out.println(mySql);
        ResultSet resultSet=null;
        try {
            resultSet=executeSQL(conn, mySql, SqlOP.SELECT, diagID);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        /**
         * 循环进行操作，扣除药库中数据,先查询剩余,再进行自减
         * 若剩余不足将抛出SQL异常
         */
        String sql_SELECT="SELECT `Remain` FROM `table_medicine` WHERE `MedId`=?";
        String sql_red="UPDATE `table_medicine` set `Rmain` = `Remain`-? WHERE `MedId` = ?";
        while (true) {
            try {
                if (!resultSet.next()) break;
                Object[] medId=new  String[] {resultSet.getString("MedId")};
                System.out.println("SELECT `Remain` FROM `table_medicine` WHERE `MedId`=?");
                ResultSet remainResultSet=executeSQL(conn,sql_SELECT,SqlOP.SELECT,medId);
                if(remainResultSet.getInt("Remain")>0){
                    System.out.println("UPDATE `table_medicine` set `Remain` = `Rmain`-? WHERE `MedId` = ?");
                    medId=new  Object[] { resultSet.getInt("Consum"),resultSet.getString("MedId")};
                    executeSQL(conn, sql_red, SqlOP.UPDATE, medId);
                }else {
                    throw new SQLException();
                }

            } catch (SQLException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        try {
            DatabaseManager.closeAll(conn, null, null);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发药，只修改处方状态
     * @param prescriptionNum
     */
    @Override
    public void comfirmMedi(String prescriptionNum) {
        String sql="UPDATE `table_prescription_medicine` set `Process` = 4 WHERE `PrescribeId` = ?";
        Connection connection=null;
        try {
            connection=getConnection();
            executeSQL(connection, sql, SqlOP.UPDATE, new String[]{prescriptionNum});
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
